package com.tughluq.smsredirector

import android.app.ActivityManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.IBinder
import android.widget.Toast

class SMSReceiverService : Service() {
    private var _receiver = SMSReceiver()
    override fun onBind(intent: Intent): IBinder? = null
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        registerReceiver(_receiver, IntentFilter().apply {
            addAction("android.provider.Telephony.SMS_RECEIVED")
        })
        Toast.makeText(baseContext, "SMS REDIRECTOR BROADCAST RECEIVER SERVICE start SUCCESSFULLY", Toast.LENGTH_LONG).show()
        return START_STICKY
    }

    override fun onDestroy() {
        Toast.makeText(baseContext, "SMS REDIRECTOR BROADCAST RECEIVER SERVICE stop SUCCESSFULLY", Toast.LENGTH_LONG).show()
        unregisterReceiver(_receiver)
    }
}


fun Context.startOrStopService(){
    val running = (getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getRunningServices(Int.MAX_VALUE).any { it.service.className == SMSReceiverService::class.java.name }

    if (myAppConfig.enabled && !running) {
        startService(Intent(this, SMSReceiverService::class.java))
    }
    if (!myAppConfig.enabled && running) {
        stopService(Intent(this, SMSReceiverService::class.java))
    }
}